package com.atguigu.yygh.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.atguigu.yygh.oss.service.FileService;
import com.atguigu.yygh.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @description: TODO
 * @author: 化一帆
 * @date: 2022/12/5 20:44
 * @version: v1.0
 */
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConstantOssPropertiesUtils.END_POINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantOssPropertiesUtils.ACCESS_KEY_SECRET;
        String bucketName = ConstantOssPropertiesUtils.BUCKET_NAME;


        // 1.创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        // 2.创建上传文件流
        try {
            //获取文件的原名称
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            filename = uuid+filename;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            filename = timeUrl+"/"+filename;

            //调用方法实现上传
            // 参数二：1.jpg    /a/b1.jpg
            ossClient.putObject(bucketName, filename,inputStream);


            //3.关闭OSSClient
            ossClient.shutdown();


            //4.返回上传之后文件的路径
            //固定路径，定义拼接
            // https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucketName+"."+endpoint+"/"+filename;

            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
